package com.it.controller;

import com.it.pojo.SysImage;
import com.it.service.SysImageService;
import com.it.utils.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class UploadController {

    @Autowired
    private SysImageService sysImageService;

    /**
     * 图片文件上传
     */
    @RequestMapping(value = "/photoUpload", method = RequestMethod.POST)
    public String photoUpload(MultipartFile file, HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) throws IllegalStateException, IOException {
        ResultData<Object> resultData = new ResultData<Object>();
        // 判断用户是否登录
        /*User user=(User) session.getAttribute("user");
         if (user==null) {
         resultData.setCode(40029);
         resultData.setMsg("用户未登录");
         return resultData;
         }*/
        try{

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            if (file != null) {// 判断上传的文件是否为空
                String path = null;// 文件路径
                String type = null;// 文件类型
                String fileName = file.getOriginalFilename();// 文件原名称
//                String stream = IOUtils.toString(file.getInputStream());
                String suffix = fileName.substring(fileName.lastIndexOf('.'), fileName.length());
                System.out.println("上传的文件原名称:" + fileName); // 判断文件类型
                type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
                if (type != null) {// 判断文件类型是否为空
                    if ("GIF".equals(type.toUpperCase()) || "PNG".equals(type.toUpperCase()) || "JPG".equals(type.toUpperCase())) { // 项目在容器中实际发布运行的根路径
                        String realPath = request.getSession().getServletContext().getRealPath("/"); // 自定义的文件名称
                        String trueFileName = sdf.format(new Date()) + "\\" + UUID.randomUUID().toString().substring(0, 10) + suffix; // 设置存放图片文件的路径
                        path = realPath + trueFileName;
                        System.out.println("存放图片文件的路径:" + path); // 转存文件到指定的路径
                        file.transferTo(new File(path));
                        System.out.println("文件成功上传到指定目录下");

                        String linkId = request.getParameter("linkId");
                        String linkType = request.getParameter("linkType");
                        String fileType = request.getParameter("fileType");
                        String isDefault = request.getParameter("isDefault");
                        String content = request.getParameter("content");
                        toSaveImageInfo(linkId, linkType, fileType, fileName, file.getSize(), suffix, content, isDefault, path, trueFileName, null);

                    } else {
                        System.out.println("不是我们想要的文件类型,请按要求重新上传");
                    }
                } else {
                    System.out.println("文件类型为空");
                }
            } else {
                System.out.println("没有找到相对应的文件");
            }
            model.addAttribute("resultData", resultData);
        }catch(RuntimeException e){
            e.printStackTrace();
        }
        String redirectPath = request.getParameter("redirectPath") + "?id=" + request.getParameter("linkId");
//        model.addAttribute("id", request.getParameter("linkId"));
        return "redirect:" + redirectPath;
//        return "test/file/index";
    }

    private void toSaveImageInfo(String linkId, String linkType, String fileType, String name, Long size, String suffix,
                          String content, String isDefault, String absoluteUrl, String relativeUrl, String stream){

        /**
         * 根据linkId和linkType查找已有图片
         */
        List<SysImage> imageDeletes = sysImageService.findByLink(linkId, Integer.parseInt(linkType));
        /**
         * 删除含有该linkId和linkType的图片信息
         */
        if(imageDeletes != null && imageDeletes.size() > 0){
            for(SysImage image:imageDeletes){
                sysImageService.deleteById(image.getId());
            }
        }
        /**
         * 保存当前的图片信息
         */
        SysImage image = new SysImage();

        image.setId(UUID.randomUUID().toString().substring(0, 32));
        image.setFileType(fileType);
        image.setName(name);
        image.setSize(size);
        image.setFormat(suffix);
        image.setContent(content);
        image.setLinkId(linkId);
        image.setLinkType(Integer.parseInt(linkType));
        image.setIsDefault(isDefault);
        image.setAbsoluteUrl(absoluteUrl);
        image.setRelativeUrl(relativeUrl);
        image.setStream(stream);

        int i = sysImageService.addSysImage(image);

        if(i > 0){
            System.out.println("完成图片的数据信息持久化。");
        }else{
            System.out.println("持久化图片信息失败，请检查后重试。");
        }

    }

}
